package queue.work;

import queue.ConnUtil;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者:消费信息,获取消息
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection conn = ConnUtil.getConn();

        //创建信道
        Channel channel = conn.createChannel();

        //队列名
        String queueName = "my-que";
        channel.queueDeclare(queueName,false,false,false,null);

        //消费者
        DefaultConsumer consumer = new DefaultConsumer(channel){
            /**
             * 应答的处理器:当消费者获取从队列中获取到消息时的回调函数,进行消费
             * @param consumerTag 消费者表示
             * @param envelope
             * @param properties 参数信息
             * @param body 消息内容
             * @throws IOException
             */
            @SneakyThrows
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 应答标识
                System.out.println("deliveryTag:"+envelope.getDeliveryTag());
                Thread.sleep(1000);
                System.out.println("获取到的消息内容:"+new String(body));

                channel.basicAck(envelope.getDeliveryTag(),true);
            }
        };


        channel.basicConsume(queueName,false,consumer);
//        channel.close();;
//        conn.close();
    }
}
